package cn.itcast.hibernate;


import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.itcast.hibernate.domain.Department;
import cn.itcast.hibernate.domain.Employee;

public class Many2One {

	public static void main(String[] args) {
		Department depart = add();
		//Employee emp = query(1);
		queryDepart(depart.getId());
	}
	
	static Employee query(int empId) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			Employee emp = (Employee)s.get(Employee.class, empId);
			System.out.println("depart name:" + emp.getDepart().getName());
			//Hibernate.initialize(emp.getDepart());
			tx.commit();
			return emp;
		} finally {
			if (s != null) 
				s.close();
		}
	}
	
	static Department queryDepart(int departId) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			Department depart = (Department)s.get(Department.class, departId);
			System.out.println("emp size:" + depart.getEmps().size());
			//Hibernate.initialize(depart.getEmps());
			tx.commit();
			return depart;
		} finally {
			if (s != null) 
				s.close();
		}
	}
	
	static Department add() {
		Session s = null;
		Transaction tx = null;
		try {
			Department depart = new Department();
			depart.setName("department1");
			Employee em = new Employee();
			em.setDepart(depart);
			em.setName("emp1");
			
			Employee emp2 = new Employee();
			emp2.setDepart(depart);
			emp2.setName("emp2");
			
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.save(depart);
			s.save(em);
			s.save(emp2);
			tx.commit();
			return depart;
		} finally {
			if (s != null) 
				s.close();
		}
	}
}
